<?php

class CategoryController extends AbstractAdminController
{

	public function actionList()
	{
		$oCategory = new Categories();
		$oStoreUrl = new StoreUrl();

		$oRowset = $oCategory->getAll();

		$oCriteria = $oStoreUrl->getDbCriteria();
		$oCriteria->group = 'category_id';
		$oCriteria->select = 'category_id, count(*) as is_new';
		$oCriteria->addColumnCondition(array('is_new' => '1', 'is_parsed' => 1));
		$oUrlRowset = $oStoreUrl->findAll($oCriteria);

		$aUrlCount = array();
		foreach($oUrlRowset as $oRow)
		{
			$aUrlCount[$oRow->category_id] = $oRow->is_new;
		}

		$this->layout='//layouts/admin';
		$this->render('list', array('oRowset' => $oRowset, 'aUrlCount' => $aUrlCount));
	}

	public function actionEditor()
	{
        $oCategory = new Categories();
        $oPhotos = new Photos();
        $oParser = new Parser();

        $id = $this->_getParam('id');

        if($this->_isPost())
        {
            $attr = $this->_getPost();
	        $attr['user_id'] = $this->_userInfo->id;

	        $oCategory = new Categories();
            if($oCategory = $oCategory->saveRow($attr))
            {
                $oPhotos->saveByTarget($oCategory, $this->_getPost());

                if($this->_isXmlHttpRequest())
                    Yii::app()->end();
                else
                    return $this->redirect(array('list'));
            }
        }

        if($this->_isXmlHttpRequest())
		    Yii::app()->end();

		if($id > 0)
		{
			$oCategory = $oCategory->findByPk($id);

			if(!$oCategory)
				return $this->redirect('/');
		}

        $oPhotos->selectAllByRow($oCategory);

        $oParsers = $oParser->findAll('enabled = 1');

        $this->render('edit', array(
            'oRow' => $oCategory,
            'oParsers' => $oParsers,
        ));
	}

	public function actionDelete($id = null)
	{
        $oCategory = new Categories();
        $oPhoto = new Photos();
        $oFiles = new Files();

        $oCategory = $oCategory->findByPk($id);

        $oPhoto->selectByRow($oCategory);

        if(!empty($oCategory) && !empty($oCategory['photos']))
        {
            foreach($oCategory['photos'] as $oPhoto)
            {
                $oFiles->deleteDirectory(PUBLIC_PATH . $oPhoto->path);

                $oPhoto->delete();
            }
        }

        $oCategory->delete();

        $returnUrl = Yii::app()->user->returnUrl;

        if(!empty($_SERVER['HTTP_REFERER']))
            $returnUrl = $_SERVER['HTTP_REFERER'];

        return $this->redirect($returnUrl);
	}

	public function actionActive($id = null)
	{
		if($id < 1)
			exit;

        $oCategory = new Categories();

        $oCategory = $oCategory->findByPk($id);

		$oCategory->updateAll(array('active' => !$oCategory->active), "id = '". $id ."'");

        $returnUrl = Yii::app()->user->returnUrl;

        if(!empty($_SERVER['HTTP_REFERER']))
            $returnUrl = $_SERVER['HTTP_REFERER'];

        return $this->redirect($returnUrl);
	}

	public function actionProperties($id)
	{
		$oCategoryProperty = new CategoryProperty();

        $oRowset = $oCategoryProperty->getAll($id);

		$this->render('properties', array(
		                                 'oRowset' => $oRowset,
		                                 'categoryId' => $id
		                            ));
	}

	public function actionPropertyAdd($id, $propertyId = null)
	{
		$oProperty = new Property();
		$oCategoryProperty = new CategoryProperty();

		$toView = array(
			'category_id' => $id,
			'property_id' => $propertyId,
			'aTypes' => $oProperty->getTypes()
		);



		if($this->_isPost())
		{
//			print_r($this->_getParam('value')); exit;
			if($oProperty = $oProperty->saveRow($this->_getPost()))
			{
				// Save property values
				$oPropertyValue = new PropertyValue();
				$oPropertyValue->saveRow(
					$oProperty->id,
					$this->_getParam('value'),
					$this->_getParam('value_id')
				);

				// Save category properties relation
				$oCategoryProperty = new CategoryProperty();
				$oCategoryProperty = $oCategoryProperty->findByAttributes(array(
				                                               'category_id' => $id,
				                                               'property_id' => $oProperty->id,
				                                          ));

				if(!$oCategoryProperty)
				{
					$oCategoryProperty = new CategoryProperty();
					$oCategoryProperty->setAttributes(array(
					                                      'category_id' => $id,
					                                      'property_id' => $oProperty->id,
					                                 ));
					$oCategoryProperty->save();
				}

				$this->redirect(Yii::app()->createUrl('/admin/category/properties/', array('id' => $id)));
			}
		}


		$oPropertyValue = new PropertyValue();

		if($propertyId > 0)
		{
			$oPropRow = $oProperty->findByPk($propertyId);

			if($oPropRow && $oPropRow->id > 0)
			{
				$oValues = $oPropertyValue->findAllByAttributes(array('property_id' => $oPropRow->id));
				$aValues = array();

				foreach($oValues as $oValue)
					$aValues[$oValue->id] = $oValue;

				$toView['oValues'] = $aValues;
			}

			$toView['oRow'] = $oPropRow;
		}

		if(empty($toView['oRow']))
			$toView['oRow'] = new Property();

//		print_r($toView); exit;

		$this->render('property-add', $toView);
	}

	public function actionPropertyDelete($id)
	{
		if($id > 0)
		{
			$oProperty = new Property();

			$oProperty->deleteAllByAttributes(array(
			                                            'id' => $id,
			                                       ));
		}

		$redirect = Yii::app()->createUrl('/admin/category/list');

		if(!empty($_SERVER['HTTP_REFERER']))
			$redirect = $_SERVER['HTTP_REFERER'];

		$this->redirect($redirect);
	}

	public function actionNewGoods($categoryId)
	{
		$toView = array();
		$toView['categoryId'] = $categoryId;

		$oStoreUrl = new StoreUrl();

		$oCriteria = $oStoreUrl->getDbCriteria();
		$oCriteria->select = 'id, data';
		$oCriteria->addCondition("data!=url AND is_new = 1 AND is_parsed = 1 AND category_id = ". $categoryId);
		$this->oPager = new CPagination($oStoreUrl->count($oCriteria));
		$this->oPager->setPageSize(10);
		$this->oPager->applyLimit($oCriteria);

		$oRowset = $oStoreUrl->findAll($oCriteria);

		$toView['oRowset'] = $oRowset;

		$this->render('new-goods', $toView);
	}

	public function actionViewNewGoods($id = 1)
	{
		$toView = array();
		$toView['id'] = $id;

		$oStoreUrl = new StoreUrl();
		$oRow = $oStoreUrl->findByPk($id);


		if($this->_isPost() && $this->_getParam('is_not_new'))
		{
			$oRow->is_new = 0;
			$oRow->save();

			echo json_encode(array('success' => true)); exit;
		}
		else if($this->_isPost() && $this->_getParam('add'))
		{
			set_time_limit(60000);
			$oGoods = new Goods();
			$oCategory = new Categories();

			$oCategory = $oCategory->findByPk($oRow->category_id);
			$aCategories = array($oCategory->id => $oCategory);

			$aUrl = array($oRow->url => $oRow);

			if(!$aUrl)
				exit;

			if($oRow->data)
			{
				$aRow = json_decode($oRow->data, true);

				if(!empty($aRow))
				{
					$oRow->is_new = 0;
					$oRow->save();

					$aRow['url'] = $oRow->url;

					$goodsId = $oGoods->saveParsedRow($aRow, $aUrl, $aCategories);

					echo json_encode(array(
						'success' => true,
						'html' => '<a href="'. Yii::app()->controller->createUrl('/admin/goods/editor/', array('id' => $goodsId)) .'">Редагувати доданий товар</a>'
					)); exit;
				}
			}
		}


		$toView['oRow'] = $oRow;

		$this->render('new-goods-view', $toView);
	}

}